#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "YourTagName"
#include "paging_controller.h"
#include <hilog/log.h>
#include <arkui/native_node.h>

#define LOG_TAG "PagingController"
#define LOGI(...) OH_LOG_Print(LOG_APP, LOG_INFO, 0, LOG_TAG, __VA_ARGS__)
#define LOGE(...) OH_LOG_Print(LOG_APP, LOG_ERROR, 0, LOG_TAG, __VA_ARGS__)

// ============ List控制器实现 ============

template<typename T>
PagingListViewController<T>::PagingListViewController() {
    // 获取Node API接口
    OH_ArkUI_GetModuleInterface(ARKUI_NATIVE_NODE, ArkUI_NativeNodeAPI_1, nodeAPI_);
    createListNode();
}

template<typename T>
PagingListViewController<T>::~PagingListViewController() {
    clearItemNodes();
    if (listNode_) {
        nodeAPI_->disposeNode(listNode_);
    }
}

template<typename T>
void PagingListViewController<T>::createListNode() {
    if (!nodeAPI_) {
        LOGE("NodeAPI is null");
        return;
    }
    
    // 创建List节点
    listNode_ = nodeAPI_->createNode(ARKUI_NODE_LIST);
    if (!listNode_) {
        LOGE("Failed to create list node");
        return;
    }
    
    // 设置List属性
    ArkUI_NumberValue widthValue[] = {{.f32 = 100}};
    ArkUI_AttributeItem widthItem = {widthValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(listNode_, NODE_WIDTH_PERCENT, &widthItem);
    
    ArkUI_NumberValue heightValue[] = {{.f32 = 100}};
    ArkUI_AttributeItem heightItem = {heightValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(listNode_, NODE_HEIGHT_PERCENT, &heightItem);
    
    // 修正：使用正确的滚动条状态常量 (2 = AUTO)
    ArkUI_NumberValue scrollBarValue[] = {{.i32 = 2}};
    ArkUI_AttributeItem scrollBarItem = {scrollBarValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(listNode_, NODE_SCROLL_BAR_DISPLAY_MODE, &scrollBarItem);
    
    LOGI("List node created successfully");
}

template<typename T>
void PagingListViewController<T>::clearItemNodes() {
    std::lock_guard<std::mutex> lock(dataMutex_);
    
    if (listNode_ && nodeAPI_) {
        // 移除所有子节点
        nodeAPI_->removeAllChildren(listNode_);
    }
    
    // 释放节点句柄
    for (auto node : itemNodes_) {
        if (node) {
            nodeAPI_->disposeNode(node);
        }
    }
    itemNodes_.clear();
}

template<typename T>
void PagingListViewController<T>::updateListItems() {
    if (!listNode_ || !itemBuilder_) {
        LOGE("List node or item builder is null");
        return;
    }
    
    clearItemNodes();
    
    std::lock_guard<std::mutex> lock(dataMutex_);
    
    // 创建新的列表项
    for (size_t i = 0; i < items_.size(); ++i) {
        auto itemNode = itemBuilder_(items_[i], static_cast<int>(i));
        if (itemNode) {
            // 创建ListItem容器
            auto listItemNode = nodeAPI_->createNode(ARKUI_NODE_LIST_ITEM);
            nodeAPI_->addChild(listItemNode, itemNode);
            nodeAPI_->addChild(listNode_, listItemNode);
            itemNodes_.push_back(listItemNode);
        }
    }
    
    LOGI("Updated list with %zu items", items_.size());
}

template<typename T>
void PagingListViewController<T>::submitData(const PagingData<T>& data) {
    {
        std::lock_guard<std::mutex> lock(dataMutex_);
        
        // 保存旧数据用于差分计算
        auto oldItems = items_;
        
        // 更新数据
        items_ = data.items;
        loadStates_ = data.loadStates;
        
        // 通知数据变化
        if (onDataChanged_) {
            onDataChanged_(0, static_cast<int>(items_.size()));
        }
        
        // 检测插入和删除
        if (items_.size() > oldItems.size() && onDataInserted_) {
            int insertPos = static_cast<int>(oldItems.size());
            int insertCount = static_cast<int>(items_.size() - oldItems.size());
            onDataInserted_(insertPos, insertCount);
        } else if (items_.size() < oldItems.size() && onDataRemoved_) {
            int removePos = static_cast<int>(items_.size());
            int removeCount = static_cast<int>(oldItems.size() - items_.size());
            onDataRemoved_(removePos, removeCount);
        }
    }
    
    // 更新UI
    updateListItems();
    
    // 通知加载状态变化
    if (onLoadStateChanged_) {
        onLoadStateChanged_(loadStates_);
    }
}

template<typename T>
void PagingListViewController<T>::refresh() {
    // 设置刷新状态
    {
        std::lock_guard<std::mutex> lock(dataMutex_);
        loadStates_.refresh.isLoading = true;
        loadStates_.refresh.isError = false;
    }
    
    if (onLoadStateChanged_) {
        onLoadStateChanged_(loadStates_);
    }
    
    // 清空数据
    items_.clear();
    updateListItems();
    
    LOGI("Refresh initiated");
}

template<typename T>
void PagingListViewController<T>::retry() {
    // 重试加载
    refresh();
}

template<typename T>
void PagingListViewController<T>::invalidate() {
    updateListItems();
}

template<typename T>
std::shared_ptr<PagingItem<T>> PagingListViewController<T>::getItem(int position) const {
    std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(dataMutex_));
    
    if (position >= 0 && position < static_cast<int>(items_.size())) {
        return items_[position];
    }
    return nullptr;
}

template<typename T>
size_t PagingListViewController<T>::getItemCount() const {
    std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(dataMutex_));
    return items_.size();
}

template<typename T>
void PagingListViewController<T>::setItemBuilder(
    std::function<ArkUI_NodeHandle(std::shared_ptr<PagingItem<T>>, int)> builder) {
    itemBuilder_ = builder;
}

template<typename T>
void PagingListViewController<T>::setDataChangeListeners(
    std::function<void(int, int)> onChanged,
    std::function<void(int, int)> onInserted,
    std::function<void(int, int)> onRemoved) {
    onDataChanged_ = onChanged;
    onDataInserted_ = onInserted;
    onDataRemoved_ = onRemoved;
}

template<typename T>
void PagingListViewController<T>::addLoadStateListener(
    std::function<void(const CombinedLoadStates&)> listener) {
    onLoadStateChanged_ = listener;
}

template<typename T>
void PagingListViewController<T>::scrollToPosition(int position) {
    if (!listNode_ || !nodeAPI_) return;
    
    // 使用List的scrollTo API
    ArkUI_NumberValue scrollValue[] = {{.i32 = position}};
    ArkUI_AttributeItem scrollItem = {scrollValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(listNode_, NODE_LIST_SCROLL_TO_INDEX, &scrollItem);
}

template<typename T>
void PagingListViewController<T>::scrollToTop() {
    scrollToPosition(0);
}

template<typename T>
void PagingListViewController<T>::scrollToBottom() {
    scrollToPosition(static_cast<int>(items_.size() - 1));
}

// ============ Grid控制器实现 ============

template<typename T>
PagingGridViewController<T>::PagingGridViewController() {
    OH_ArkUI_GetModuleInterface(ARKUI_NATIVE_NODE, ArkUI_NativeNodeAPI_1, nodeAPI_);
    createGridNode();
}

template<typename T>
PagingGridViewController<T>::~PagingGridViewController() {
    clearItemNodes();
    if (gridNode_) {
        nodeAPI_->disposeNode(gridNode_);
    }
}

template<typename T>
void PagingGridViewController<T>::createGridNode() {
    if (!nodeAPI_) {
        LOGE("NodeAPI is null");
        return;
    }
    
    // 创建Grid节点
    gridNode_ = nodeAPI_->createNode(ARKUI_NODE_GRID);
    if (!gridNode_) {
        LOGE("Failed to create grid node");
        return;
    }
    
    // 设置Grid属性
    ArkUI_NumberValue widthValue[] = {{.f32 = 100}};
    ArkUI_AttributeItem widthItem = {widthValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(gridNode_, NODE_WIDTH_PERCENT, &widthItem);
    
    ArkUI_NumberValue heightValue[] = {{.f32 = 100}};
    ArkUI_AttributeItem heightItem = {heightValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(gridNode_, NODE_HEIGHT_PERCENT, &heightItem);
    
    // 修正：使用正确的列模板属性名
    ArkUI_AttributeItem columnsItem = {nullptr, 0, columnsTemplate_.c_str(), nullptr};
    nodeAPI_->setAttribute(gridNode_, NODE_GRID_COLUMN_TEMPLATE, &columnsItem);
    
    // 修正：分别设置列间距和行间距
    ArkUI_NumberValue columnGapValue[] = {{.f32 = columnGap_}};
    ArkUI_AttributeItem columnGapItem = {columnGapValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(gridNode_, NODE_GRID_COLUMN_GAP, &columnGapItem);
    
    ArkUI_NumberValue rowGapValue[] = {{.f32 = rowGap_}};
    ArkUI_AttributeItem rowGapItem = {rowGapValue, 1, nullptr, nullptr};
    nodeAPI_->setAttribute(gridNode_, NODE_GRID_ROW_GAP, &rowGapItem);
    
    LOGI("Grid node created successfully");
}

template<typename T>
void PagingGridViewController<T>::clearItemNodes() {
    std::lock_guard<std::mutex> lock(dataMutex_);
    
    if (gridNode_ && nodeAPI_) {
        nodeAPI_->removeAllChildren(gridNode_);
    }
    
    for (auto node : itemNodes_) {
        if (node) {
            nodeAPI_->disposeNode(node);
        }
    }
    itemNodes_.clear();
}

template<typename T>
void PagingGridViewController<T>::updateGridItems() {
    if (!gridNode_ || !itemBuilder_) {
        LOGE("Grid node or item builder is null");
        return;
    }
    
    clearItemNodes();
    
    std::lock_guard<std::mutex> lock(dataMutex_);
    
    for (size_t i = 0; i < items_.size(); ++i) {
        auto itemNode = itemBuilder_(items_[i], static_cast<int>(i));
        if (itemNode) {
            // 创建GridItem容器
            auto gridItemNode = nodeAPI_->createNode(ARKUI_NODE_GRID_ITEM);
            nodeAPI_->addChild(gridItemNode, itemNode);
            nodeAPI_->addChild(gridNode_, gridItemNode);
            itemNodes_.push_back(gridItemNode);
        }
    }
    
    LOGI("Updated grid with %zu items", items_.size());
}

template<typename T>
void PagingGridViewController<T>::submitData(const PagingData<T>& data) {
    {
        std::lock_guard<std::mutex> lock(dataMutex_);
        
        auto oldItems = items_;
        items_ = data.items;
        loadStates_ = data.loadStates;
        
        if (onDataChanged_) {
            onDataChanged_(0, static_cast<int>(items_.size()));
        }
        
        // 检测插入和删除
        if (items_.size() > oldItems.size() && onDataInserted_) {
            int insertPos = static_cast<int>(oldItems.size());
            int insertCount = static_cast<int>(items_.size() - oldItems.size());
            onDataInserted_(insertPos, insertCount);
        } else if (items_.size() < oldItems.size() && onDataRemoved_) {
            int removePos = static_cast<int>(items_.size());
            int removeCount = static_cast<int>(oldItems.size() - items_.size());
            onDataRemoved_(removePos, removeCount);
        }
    }
    
    updateGridItems();
}

template<typename T>
void PagingGridViewController<T>::refresh() {
    {
        std::lock_guard<std::mutex> lock(dataMutex_);
        loadStates_.refresh.isLoading = true;
        loadStates_.refresh.isError = false;
    }
    
    items_.clear();
    updateGridItems();
    
    LOGI("Grid refresh initiated");
}

template<typename T>
void PagingGridViewController<T>::retry() {
    refresh();
}

template<typename T>
std::shared_ptr<PagingItem<T>> PagingGridViewController<T>::getItem(int position) const {
    std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(dataMutex_));
    
    if (position >= 0 && position < static_cast<int>(items_.size())) {
        return items_[position];
    }
    return nullptr;
}

template<typename T>
size_t PagingGridViewController<T>::getItemCount() const {
    std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(dataMutex_));
    return items_.size();
}

template<typename T>
void PagingGridViewController<T>::setColumnsTemplate(const std::string& template_) {
    columnsTemplate_ = template_;
    
    if (gridNode_ && nodeAPI_) {
        // 修正：使用正确的属性名
        ArkUI_AttributeItem columnsItem = {nullptr, 0, columnsTemplate_.c_str(), nullptr};
        nodeAPI_->setAttribute(gridNode_, NODE_GRID_COLUMN_TEMPLATE, &columnsItem);
    }
}

template<typename T>
void PagingGridViewController<T>::setGaps(float columnGap, float rowGap) {
    columnGap_ = columnGap;
    rowGap_ = rowGap;
    
    if (gridNode_ && nodeAPI_) {
        // 修正：分别设置列间距和行间距
        ArkUI_NumberValue columnGapValue[] = {{.f32 = columnGap_}};
        ArkUI_AttributeItem columnGapItem = {columnGapValue, 1, nullptr, nullptr};
        nodeAPI_->setAttribute(gridNode_, NODE_GRID_COLUMN_GAP, &columnGapItem);
        
        ArkUI_NumberValue rowGapValue[] = {{.f32 = rowGap_}};
        ArkUI_AttributeItem rowGapItem = {rowGapValue, 1, nullptr, nullptr};
        nodeAPI_->setAttribute(gridNode_, NODE_GRID_ROW_GAP, &rowGapItem);
    }
}

template<typename T>
void PagingGridViewController<T>::setItemBuilder(
    std::function<ArkUI_NodeHandle(std::shared_ptr<PagingItem<T>>, int)> builder) {
    itemBuilder_ = builder;
}

template<typename T>
void PagingGridViewController<T>::setDataChangeListeners(
    std::function<void(int, int)> onChanged,
    std::function<void(int, int)> onInserted,
    std::function<void(int, int)> onRemoved) {
    onDataChanged_ = onChanged;
    onDataInserted_ = onInserted;
    onDataRemoved_ = onRemoved;
}

// 显式实例化常用类型
template class PagingListViewController<std::string>;
template class PagingGridViewController<std::string>;